import React from 'react'
import { Form, Input, Button, Checkbox } from 'antd';
import style from './RegisterForm.module.css'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'

export const RegisterForm = () => {
  let navigate = useNavigate();
  const [form] = Form.useForm();
  const onFinish = async (values: any) => {
    console.log('Success:', values);
    try {
      await axios.post("https://mock.mengxuegu.com/mock/61c70e2ebba8817f8a413580/tourism_website/register", {
        email: values.username,
        password: values.password,
        confirmPassword: values.confirm
      })
      navigate("/signIn/")
    } catch (error) {
      alert('注册失败!!')
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const handleValidator = () => {
    // console.log(e, 999)
    console.log(form, 999000)
    if(form.getFieldValue("password") === form.getFieldValue("Confirm")) {
      // 验证成功
      return Promise.resolve()
    }
    return Promise.reject("密码确认不一致")
}

// (({getFieldValue}) => {
//   // value 传递进来的数据
//   validator(_, value) {
//     // 获取password字段的值
//     if(!value || getFieldValue("password") === value) {
//       // 验证成功
//       return Promise.resolve()
//     }
//     Promise.reject("密码确认不一致")
//   }
// })


  return (
    <Form
      form={form} 
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
      className={style.registerForm}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[{ required: true, message: 'Please input your password!' }]}
      >
        <Input.Password />
      </Form.Item>
      {/* 密码确认 */}
      <Form.Item
        label="Confirm Password"
        name="Confirm"
        rules={[
          { required: true, message: 'Please input your Confirm password!' },
          { validator: handleValidator }
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};
